package com.invexer.common.controller.init {
import com.invexer.common.puremvc.patterns.command.InvexerSimpleCommandBase;

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;

import mx.core.FlexGlobals;

import org.as3commons.logging.ILogger;

import org.as3commons.logging.LoggerFactory;

import org.puremvc.as3.multicore.interfaces.INotification;

import spark.components.Application;

public class ContextInitConfigCMD extends InvexerSimpleCommandBase {
	private static var logger : ILogger = LoggerFactory.getClassLogger(ContextInitConfigCMD);

	private var mOnCompleteCallback:Function;

	override public function execute(notification:INotification):void{
		super.execute(notification);
		
		var data:Object = notification.getBody();
		mOnCompleteCallback = data.callback;
		
		var urlLoader:URLLoader = new URLLoader();
		urlLoader.addEventListener(ProgressEvent.PROGRESS, urlLoaderOnProgress);
		urlLoader.addEventListener(Event.COMPLETE, urlLoaderOnComplete);
		urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlLoaderOnIoError);
		urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, urlLoaderOnSecurityError);
		var app:Application = FlexGlobals.topLevelApplication as Application;
		var path:String = app.url.substring(0, app.url.lastIndexOf("/")+1) + data.appConfigPath;
		logger.debug("appConfig file appConfigPath: " + path)
		var urlRequest:URLRequest = new URLRequest(data.appConfigPath);

 		urlLoader.load(urlRequest);

	}

	private function urlLoaderOnProgress(event:ProgressEvent):void {
	}
	private function urlLoaderOnComplete(event:Event):void {
		var target:URLLoader = event.currentTarget as URLLoader;
		var data:Object = JSON.parse(target.data);

		logger.debug("urlLoaderOnComplete:\n" + JSON.stringify(data));

		mOnCompleteCallback(data);
		target.close();

	}
	private function urlLoaderOnIoError(event:IOErrorEvent):void{
		logger.error("IOERROR : " + event.toString());
	}
	private function urlLoaderOnSecurityError(event:SecurityErrorEvent):void{
		logger.error("SECURITY_ERROR : " + event);
	}
}
}
